package com.liu.juc.forkjoin;

import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 计算从1到10_0000_0000 相加的和
 */
public class Demo1 {
    /**
     * 方式一 最普通的工程师
     * sum=500000000500000000-- 时间花费:3852
     */
    @Test
    public void Test() {
        Long sum = 0L;
        long l = System.currentTimeMillis();
        for (int i = 0; i <= 10_0000_0000; i++) {
            sum += i;
        }
        System.out.println("sum=" + sum + "-- 时间花费:" + (System.currentTimeMillis() - l));
    }

    /**
     * 使用forkjoin 拆分连接  中级程序员
     * sum=500000000500000000-- 时间花费:5491
     */
    @Test
    public void Test1() throws ExecutionException, InterruptedException {
        long l = System.currentTimeMillis();
        Long sum = 0L;
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo1 joinDemo1 = new ForkJoinDemo1(0L, 10_0000_0001L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(joinDemo1);
        sum = submit.get();
        System.out.println("sum=" + sum + "-- 时间花费:" + (System.currentTimeMillis() - l));
    }


    /**
     * 使用stream 的并发流   高级工程师
     * 如果没有使用并发流   sum = LongStream.range(0L, 10_0000_0001l).sum(); 时间  sum=500000000500000000-- 时间花费:1746
     * 使用并发流：  sum = LongStream.range(0L, 10_0000_0001l).parallel().reduce(0L, Long::sum);  sum=500000000500000000-- 时间花费:447
     */
    @Test
    public void Test2() {
        long l = System.currentTimeMillis();
        Long sum = 0L;
        sum = LongStream.range(0L, 10_0000_0001l).parallel().reduce(0L, Long::sum);
        System.out.println("sum=" + sum + "-- 时间花费:" + (System.currentTimeMillis() - l));
    }


}
